///////////////////////////////////////////////////////////////////////////////////////////
// Description:
//   PWM support for the Freescale i.MXS processor
//
// Legal Notices:
//   Copyright (c) 2008, Telliam Consulting, LLC.
//   All rights reserved.
//
//   Redistribution and use in source and binary forms, with or without modification,
//   are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice, this list
//     of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice, this
//     list of conditions and the following disclaimer in the documentation and/or other
//     materials provided with the distribution.
//   * Neither the name of Telliam Consulting nor the names of its contributors may be
//     used to endorse or promote products derived from this software without specific
//     prior written permission.
//
//   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
//   EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
//   SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
//   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
//   BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
//   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
//   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
//   DAMAGE. 
//
using System;
using Microsoft.SPOT;
using FusionWare.SPOT.Native;

namespace FusionWare.SPOT.Hardware.iMXS
{
    /// <summary>id mapping for virtual port interop devices</summary>
    /// <remarks>
    /// These IDs *MUST* be kept in sync with the virtual serial port
    /// implementation in the HAL native code. 
    /// </remarks>
    internal enum vportid : int
    {
        VPORT_DEV_PWM = 0xEF01,
    }

    /// <summary>Class for supporting the Pulse Width Modulator (PWM) built into the iMXS CPU</summary>
    /// <remarks>
    /// The HAL must support Virtual Serial Port 0xEF01 for the PWM.
    /// The only HAL known to support that at the time of this writing is the Device Solutions
    /// (Formerly EmbeddedFusion) Meridian V2 SP1. However, Any HAL writer can implement support
    /// for this.
    /// </remarks>
    public class PWM : DisposableObject
    {
        // only one communication channel required so make it static
        static VPortDriver VPortChannel;

        // data structure serialized to the virtual port for the HAL
        [Serializable]
        class PWMData
        {
            public uint Frequency;
            public uint Duty;
            // note: placement of this last is important
            // for alignment issues in the native code
            public bool Enable;
        }

        // use a single data structure to prevent heap thrashing and
        // fragmentation on regular updates.
        PWMData Data = new PWMData();

        #region IDisposable Support
        /// <summary>Disposes the internal data</summary>
        /// <param name="disposing">Flag to indicate context of the dispose</param>
        override protected void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if(!base.IsDisposed)
            {
                // If disposing is true, dispose managed resources.
                if(disposing)
                {
                    VPortChannel.Dispose();
                    VPortChannel = null;
                }

                // in either case, dispose unmanaged resources
                // None for this class...
            }
        }
        #endregion

        /// <summary>Creates a new PWM instance</summary>
        /// <remarks>
        /// Since there is only one PWM on the CPU only one
        /// instance of this class is allowed. This constructor
        /// will throw an exception if the PWM is already in use.
        /// </remarks>
        /// <exception cref="InvalidOperationException">PWM is already in use</exception>
        public PWM()
        {
            if(PWM.VPortChannel != null)
                throw new InvalidOperationException("PWM already in use");

            PWM.VPortChannel = new VPortDriver( (int)vportid.VPORT_DEV_PWM );
        }

        /// <summary>Disables the PWM and stops all output clocking</summary>
        public void Disable()
        {
            lock( this.Data )
            {
                this.Data.Enable = false;
                PWM.VPortChannel.Write(Data);
            }
        }

        /// <summary>Configures the PWM for the specified Frequency and Duty Cycle</summary>
        /// <param name="Frequency">Frequency of the PWM Output</param>
        /// <param name="Duty">Duty cycle for the PWM Output (0-100)</param>
        /// <remarks>
        /// This method will enable the PWM if it is not already enabled
        /// and set the output Frequency and duty cycle as specified. 
        /// </remarks>
        public void Configure( uint Frequency, uint Duty )
        {
            lock( this.Data )
            {
                this.Data.Frequency = Frequency;
                this.Data.Duty = Duty;
                this.Data.Enable = true;
                PWM.VPortChannel.Write(Data);
            }
        }
    }
}
